package com.lemon.core.validator.utils;

import com.lemon.core.base.util.CheckUtils;

/**
 * Luhn算法工具类，用于检测银行卡卡号
 *
 * @author pan
 * @since 2017-11-17
 */
public class LuhnUtils {
    private LuhnUtils() {
    }

    /**
     * 匹配Luhn算法
     */
    public static boolean matchLuhn(String cardNo) {
        if (CheckUtils.isBlank(cardNo)) {
            return false;
        }
        int[] cardNoArr = new int[cardNo.length()];
        for (int i = 0; i < cardNo.length(); i++) {
            cardNoArr[i] = Integer.valueOf(String.valueOf(cardNo.charAt(i)));
        }
        for (int i = cardNoArr.length - 2; i >= 0; i -= 2) {
            cardNoArr[i] <<= 1;
            cardNoArr[i] = cardNoArr[i] / 10 + cardNoArr[i] % 10;
        }
        int sum = 0;
        for (int i = 0; i < cardNoArr.length; i++) {
            sum += cardNoArr[i];
        }
        return sum % 10 == 0;
    }

}
